package com.yimi.policyservice.service.impl;

import com.github.pagehelper.Page;
import com.yimi.policyservice.common.expetion.ApiException;
import com.yimi.policyservice.dao.optr.OptrCompMapperCustom;
import com.yimi.policyservice.dto.enums.DataPermissionEnum;
import com.yimi.policyservice.dto.optr.OptrComp4Create;
import com.yimi.policyservice.dto.optr.OptrCompAccountDto;
import com.yimi.policyservice.dto.optr.OptrCompDto;
import com.yimi.policyservice.dto.policyaddr.IdsBean;
import com.yimi.policyservice.entity.base.optr.OptrComp;
import com.yimi.policyservice.entity.base.optr.OptrCompAccount;
import com.yimi.policyservice.entity.base.system.SysUser;
import com.yimi.policyservice.repository.CompRepositroy;
import com.yimi.policyservice.repository.OptrAccountRepository;
import com.yimi.policyservice.service.OptrCompService;
import com.yimi.policyservice.service.UserDataPermissionService;
import com.yimi.policyservice.utils.BeanHelper;
import com.yimi.policyservice.utils.TokenUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class OptrCompServiceImpl implements OptrCompService {

    @Autowired
    private CompRepositroy compRepositroy ;

    @Autowired
    private OptrAccountRepository optrAccountRepository ;

    @Autowired
    private OptrCompMapperCustom optrCompMapperCustom ;

    @Autowired
    UserDataPermissionService userDataPermissionService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OptrCompDto create(OptrCompDto bean, SysUser loginUser) {
        OptrComp optrComp = new OptrComp();
        optrComp.setCreateDate(new Date());
        optrComp.setCreatorId(loginUser.getId());
        BeanUtils.copyProperties(bean,optrComp);
        optrComp.setId(null);
        compRepositroy.save(optrComp);
        bean.setId(optrComp.getId());
        //插入权限（权限存在就忽略）能有修改和添加代表有权限
        userDataPermissionService.addDataPermission(loginUser.getId(),optrComp.getId(), DataPermissionEnum.COMPANY.getValue());
        return bean;
    }

    @Override
    public void addCompanyAccount(List<OptrCompAccountDto> accountDtos) {
       List<String> accounts = new ArrayList<>();
       accountDtos.forEach(acc->{
           accounts.add(acc.getAccount());
       });
//       List<OptrCompAccount> accBuffer =  optrAccountRepository.findByAccountIn(accounts);
//       if(!accBuffer.isEmpty()){
//           throw  new ApiException(400,"社保/公积金账号重复");
//       }
       for(OptrCompAccountDto dto :accountDtos){
           OptrCompAccount account = new OptrCompAccount();
           BeanUtils.copyProperties(dto,account);
           optrAccountRepository.save(account);
       }
    }


    @Override
    public Page<OptrCompDto> search( String key, int type) {
        String userId = TokenUtil.getLoginUserId();
        return optrCompMapperCustom.search(key,type,userId);
    }


    @Override
    public List<OptrCompDto> findAll() {
        return optrCompMapperCustom.findAll();
    }

    @Override
    public List<OptrCompDto> findAllPermission(String userId){
        return optrCompMapperCustom.findAllPermission(userId);
    }

    @Override
    public OptrComp4Create view(String id) {
        OptrComp4Create res = new OptrComp4Create();
        OptrComp optrComp = compRepositroy.findById(id).get();
        OptrCompDto optrCompDto =new OptrCompDto();
        BeanUtils.copyProperties(optrComp,optrCompDto);
        res.setCompany(optrCompDto);
        List<OptrCompAccount> accountDtos = optrAccountRepository.findByOptrCompIdAndAccountType(optrComp.getId(),0);
        res.setSolicyAccounts(BeanHelper.convertList(accountDtos,OptrCompAccount.class,OptrCompAccountDto.class));
        List<OptrCompAccount> accountDtos1 = optrAccountRepository.findByOptrCompIdAndAccountType(optrComp.getId(),1);
        res.setAccfundAccounts(BeanHelper.convertList(accountDtos1,OptrCompAccount.class,OptrCompAccountDto.class));
        return res;
    }


    @Override
    @Transactional
    public void update(String id, OptrComp4Create bean,SysUser sysUser) {
        OptrComp comp = compRepositroy.findById(id).get();
        BeanHelper.copyUpdatedProperties(bean.getCompany(),comp,BeanHelper.getProperties(OptrCompDto.class));
        compRepositroy.save(comp);
        updateAccount(bean.getSolicyAccounts(),sysUser,id,0);
        updateAccount(bean.getAccfundAccounts(),sysUser,id,1);
    }

    @Override
    public  int validateCompName(String id,Integer serviceType,String name){
        if(StringUtils.isBlank(name)||serviceType==0){
            return 0;
        }
        int count=0;
        if(StringUtils.isNotBlank(id)){
             count = compRepositroy.countByNameAndType(name, serviceType,id);
        }else{
             count = compRepositroy.countByNameAndType(name, serviceType);
        }
        if(count>0){
            return 1;
        }else{
            return 0;
        }
    }
    private void updateAccount(List<OptrCompAccountDto> accountDtos,SysUser sysUser,String companyId,int type){
        List<String> ids = new ArrayList<>();
        for(OptrCompAccountDto accountDto : accountDtos){

            OptrCompAccount optrCompAccount = StringUtils.isNotBlank(accountDto.getId()) ? optrAccountRepository.findById(accountDto.getId()).get() :null;
            if(optrCompAccount == null){
                optrCompAccount  = new OptrCompAccount();
                optrCompAccount.setCreatorId(sysUser.getId());
                optrCompAccount.setCreateTime(new Date());
                optrCompAccount.setCreatorName(sysUser.getName());
                optrCompAccount.setOptrCompId(companyId);
                optrCompAccount.setAccountType(type);
            }
            optrCompAccount.setUpdateTime(new Date());
            optrCompAccount.setUpdatorId(sysUser.getId());
            BeanHelper.copyUpdatedProperties(accountDto,optrCompAccount,BeanHelper.getProperties(OptrCompAccountDto.class));
            optrAccountRepository.save(optrCompAccount);
            ids.add(optrCompAccount.getId());

        }
        if(!ids.isEmpty()){
            optrAccountRepository.deleteByCompIdInAndIdNotIn(companyId,ids,type);
        }else{
            optrAccountRepository.deleteByCompId(companyId,type);
        }

    }

    @Override
    public void delete(IdsBean bean) {
        checkCompanyUsed(bean.getIds());
        compRepositroy.deleteByIdIn(bean.getIds());
        optrAccountRepository.deleteByCompIdIn(bean.getIds());
    }


    private void checkCompanyUsed(List<String> ids) {
       int c =  compRepositroy.checkUsed(ids);
       if(c!=0){
           throw  new ApiException(400,"服务公司被引用，不能删除");
       }
    }


    @Override
    public List<OptrCompAccountDto> findAccountByCompanyId(String id, int type) {
        List<OptrCompAccount> accounts = optrAccountRepository.findByOptrCompIdAndAccountType(id,type);
        return BeanHelper.convertList(accounts,OptrCompAccount.class,OptrCompAccountDto.class);
    }

    @Override
    public void checkAccount(String companyId, String accountId) {
        int c = optrAccountRepository.check(companyId,accountId);
        if(c!=0){
            throw  new ApiException(400,"账号被使用，不能删除");
        }
    }
}
